/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jpa.controller;

import general.util.StringUtil;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import jpa.controller.exceptions.NonexistentEntityException;
import jpa.entity.Fornecedor;

/**
 *
 * @author isaias
 */
public class FornecedorJpaController {

    public FornecedorJpaController() {
        emf = Persistence.createEntityManagerFactory("ProjectObraPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Fornecedor fornecedor) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(fornecedor);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Fornecedor fornecedor) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            fornecedor = em.merge(fornecedor);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = fornecedor.getId();
                if (findFornecedor(id) == null) {
                    throw new NonexistentEntityException("The fornecedor with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Fornecedor fornecedor;
            try {
                fornecedor = em.getReference(Fornecedor.class, id);
                fornecedor.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The fornecedor with id " + id + " no longer exists.", enfe);
            }
            em.remove(fornecedor);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Fornecedor> findFornecedorAjaxName(String nameFilter, int max_results) {
        String sql = "SELECT f FROM Fornecedor f WHERE f.name LIKE :name";

        Query query = getEntityManager().createQuery(sql);

        query.setParameter("name", "%" + nameFilter.toUpperCase() + "%");

        query.setMaxResults(max_results);

        try {
            return query.getResultList();
        } catch (Exception ex) {
            ex.printStackTrace();
            return new ArrayList<Fornecedor>();
        }
    }

    public List<Fornecedor> findFornecedorEntitiesByName(String filterName) {
        String sql = "SELECT f FROM Fornecedor f ";

        String where = "";

        if (!StringUtil.isNullOrEmpty(filterName)) {

            sql += " WHERE f.name LIKE :name ";
        }

        sql += " ORDER BY f.name";

        EntityManager em = getEntityManager();

        try {
            Query query = em.createQuery(sql);

            if (!StringUtil.isNullOrEmpty(filterName)) {
                query.setParameter("name", "%" + filterName.toUpperCase() + "%");
            }

            return query.setMaxResults(6).getResultList();
        } catch (Exception ex) {
            ex.printStackTrace();
            return new ArrayList<Fornecedor>();
        } finally {
            em.close();
        }
    }

     public Fornecedor findFornecedorForName(String name) {
        String sql = "SELECT f FROM  Fornecedor f WHERE f.name LIKE :name";

        EntityManager em = getEntityManager();

        try {
            return (Fornecedor) em.createQuery(sql).setParameter("name", name.toUpperCase()).setMaxResults(1).getSingleResult();
        } catch (Exception ex) {
            if (!(ex instanceof NoResultException)) {
                ex.printStackTrace();
            }
            return null;
        } finally {
            em.close();
        }
    }


    public List<Fornecedor> findFornecedorEntities() {
        return findFornecedorEntities(true, -1, -1);
    }

    public List<Fornecedor> findFornecedorEntities(int maxResults, int firstResult) {
        return findFornecedorEntities(false, maxResults, firstResult);
    }

    private List<Fornecedor> findFornecedorEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Fornecedor.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Fornecedor findFornecedor(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Fornecedor.class, id);
        } finally {
            em.close();
        }
    }

    public int getFornecedorCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Fornecedor> rt = cq.from(Fornecedor.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
